package cn.tannn.cat.file.server.controller.rpc;

import cn.tannn.cat.file.api.FileOperateApi;
import cn.tannn.cat.file.api.entity.FileIndexVO;
import cn.tannn.cat.file.sdk.api.UploadFile;
import cn.tannn.cat.file.sdk.api.UploadFiles;
import cn.tannn.cat.file.sdk.core.ftp.FtpUtils;
import cn.tannn.cat.file.sdk.enums.StorageDict;
import cn.tannn.cat.file.sdk.utils.ResponseFile;
import cn.tannn.cat.file.server.service.FileIndexMetaService;
import cn.tannn.cat.file.server.service.FileOperateService;
import cn.tannn.jdevelops.annotations.web.mapping.PathRestController;
import cn.tannn.jdevelops.result.response.ResultVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * 文件操作接口实现  - RPC 接口
 *
 * @author <a href="https://tannn.cn/">tan</a>
 * @date 2024/3/15 14:03
 */
@Tag(name = "文件操作RPC", description = "文件操作RPC")
@PathRestController("operation")
@RequiredArgsConstructor
@Slf4j
public class FileOperateController implements FileOperateApi {

    private final FileOperateService fileOperateService;
    private final FileIndexMetaService fileIndexMetaService;

    @Override
    public ResultVO<FileIndexVO> upload(UploadFile upload) throws IOException {
        return ResultVO.success(fileOperateService.upload(upload).toFileStorageVO());
    }

    @Override
    public ResultVO<FileIndexVO> upload(Long storageId, UploadFile upload) throws IOException {
        return ResultVO.success(fileOperateService.upload(storageId, upload).toFileStorageVO());
    }

    @Override
    public ResultVO<String> uploads(UploadFiles uploads) throws IOException {
        fileOperateService.uploads(uploads);
        return ResultVO.success("批量上传成功");
    }

    @Override
    public ResultVO<String> uploads(Long storageId, UploadFiles uploads) throws IOException {
        fileOperateService.uploads(storageId, uploads);
        return ResultVO.success("批量上传成功");
    }

    @Override
    public void download(Long fileIndexId, HttpServletResponse response) {
        fileOperateService.download(fileIndexId, response);
    }


    @Override
    public ResultVO<String> remove(Long fileIndexId) {
        fileOperateService.remove(fileIndexId);
        return ResultVO.successMessage("删除成功");
    }

    @Override
    public ResultVO<String> privatizedUrl(Long fileIndexId, Integer expires) {
        return ResultVO.success(fileOperateService.previewFile(fileIndexId, expires));
    }

    @Override
    public void views(String storage, String filePath, HttpServletResponse response) {
        fileIndexMetaService.findPathAndStorage(filePath, StorageDict.fromValue(storage)).ifPresent(index -> {
            FTPClient ftpClient = FtpUtils.createFtpClient(index.getStorageId());
            try {
                // remote:文件存储在FTP的位置
                String fileNameEncoding = new String(index.getPath().getBytes(StandardCharsets.UTF_8)
                        , StandardCharsets.ISO_8859_1);
                InputStream inputStream = ftpClient.retrieveFileStream(fileNameEncoding);

                HttpServletResponse downResponse = ResponseFile.customResponse(response
                        , index.getType(), index.getFreshName());
                downResponse.setContentType("application/octet-stream");
                //设置文件大小
                downResponse.setHeader("Content-Length", String.valueOf(index.getSize()));
                IOUtils.copy(inputStream, downResponse.getOutputStream());
            } catch (Exception e) {
                log.error("ftp文件view失败：index id : {} , URL: {}", index.getId(), index.getUrl(), e);
            }finally {
                FtpUtils.disConnection(ftpClient);
            }
        });
    }
}
